<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Brick\Money\Money;
use Brick\Money\Currency;
use Webmozart\PathUtil\Path;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Carbon;
use App\Service\Model\ApiLog;

if (!function_exists('loadMonoLogger')) {
    /**
     * 加载扩展日志库
     * @param string $name
     * @return Logger
     */
    function loadMonoLogger($name, $level = Logger::INFO)
    {
        $logger = new Logger($name);
        $hander = new StreamHandler(storage_path("logs/{$name}.log"), $level);
        $logger->pushHandler($hander);
        return $logger;
    }
}

if (!function_exists('getMillisecond')){
    // 毫秒级时间戳
    function getMillisecond(){
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
}

if (!function_exists('stringToBoolean')) {
    /**
     * 字符串转逻辑值
     * @param string $src
     * @return Boolean
     */
    function stringToBoolean($src) {
        switch (trim(strtolower($src))) {
            case "true": case "yes": case "1": case "on": return true;
            case "false": case "no": case "0": case "off": case "": case null: return false;
            default: return !!$src;
        }
    }
}

if (! function_exists('user')){
    /**
     * 获取已登陆用户信息
     * @param string $parameter
     * @return \app\User|mixed
     */
    function user($parameter = null){
        if (!\Auth::check()) {
            return null;
        }
        if ($parameter) {
            return \Auth::user()->$parameter;
        }
        return \Auth::user();
    }
}

if (! function_exists('rmb')){
    /**
     * 人民币
     * @param number|string $amount
     * @return Brick\Money\Money
     */
    function rmb(string $amount){
        return Money::of($amount, Currency::of("CNY"));
    }
}

if (! function_exists('rmbPlus')) {
    /**
     * 人民币加法
     * @param string $amount
     * @param string ...$amount1
     * @return Brick\Money\Money
     */
    function rmbPlus(string $amount, string ...$amount1) {
        $money = rmb($amount);
        foreach($amount1 as $value)
            $money = $money->plus(rmb($value));
        return $money;
    }
}

if (! function_exists('rmbMinus')) {
    /**
     * 人民币减法
     * @param string $amount
     * @param string ...$amount1
     * @return Brick\Money\Money
     */
    function rmbMinus(string $amount, string ...$amount1) {
        $money = rmb($amount);
        foreach($amount1 as $value)
            $money = $money->minus(rmb($value));
        return $money;
    }
}

if (! function_exists('toAmount')){
    /**
     * 金额转换为浮点值
     * @param Brick\Money\Money $money
     * @return float
     */
    function toAmount($money){
        return $money->getAmount()->toFloat();
    }
}

if (! function_exists('loadLibrary')) {
    /**
     * Loads and instantiates helpers.
     * Designed to be called from application controllers.
     *
     * @param   string  $library Library name
     * @param   string  $class_name An optional object name to assign to
     * @param   array   $params Optional parameters to pass to the library class constructor
     * @return  object|array
     */
    function loadLibrary($library, $class_name = null, $params = []){
        $name = Path::getFilename($library);
        $path = Path::join(__DIR__, "Libraries", $name . ".php");
        if (!file_exists($path)) {
            throw new FileNotFoundException("{$path} file not found!");
        }
        include_once($path);
        if (is_string($class_name)) {
            return isset($params)
            ? new $class_name(...$params)
            : new $class_name();
        }
    }
}

if(!function_exists('randomNum')){
    /**
     * 返回随机数
     *
     * @param integer $length
     * @return string
     */
    function randomNum( $length = 10){
        $arr    =   [0,1,2,3,4,5,6,7,8,9];
        $random =   '';
        for($i=0;$i<$length;$i++){
            $index   = mt_rand(0,9);
            $random .= $arr[$index];
        }
        return $random;
    }
}


if(!function_exists('objectToString')){
    /**
     * 对象转换成没有编码的字符串
     *
     * @param object $obj
     * @return string
     */
    function objectToString($obj){
        return json_encode($obj,JSON_UNESCAPED_UNICODE);
    }
}


if(!function_exists('generate_orderId')){
    function generate_orderId($prefix = ''){
        $date = Carbon::now()->formatLocalized("%Y%m%d%H%M%S");
        $rand = rand(1000 ,9999);
        return $prefix . $date . $rand;
    }
}

if(!function_exists('apiLog')){

    function apiLog($url , $code , $request , $response){
        ApiLog::create([
            'api_url'   =>  $url,
            'code'      =>  $code,
            'request'   =>  objectToString($request),
            'response'  =>  objectToString($response),
        ]);
    }

}


if(!function_exists('getRandomNumber')){
    function getRandomNumber($totalNumber , $max_amount){
        $count       = intval($totalNumber/$max_amount);
        if($totalNumber < 1000 && $max_amount >= $totalNumber){
            return [$totalNumber];
        }else{
            $max = $max_amount;
            $min = intval($max_amount*0.8);
        }
        for($i=0;$i<$count;$i++){
            $arr[] = mt_rand($min,$max);
        }
        $last = $totalNumber - array_sum($arr);
        if($last > $max_amount){
            $arr2 =  getRandomNumber($last , $max_amount);
            $arr  =  array_merge($arr,$arr2);
        }else{
            $arr[]   = $last;
        }
        return $arr;
    }
}


if(!function_exists('getRandomTime')){
    
    function getRandomTime($datetime){
        $hour    = 1;
        $min     = rand(1,59);
        $sec     = rand(1,59);
        
        $morning = Carbon::parse($datetime)->tomorrow()->addHour($hour)->addMinute($min)->addSeconds($sec);
        return $morning;
    }

}
